/* eslint-disable no-use-before-define */
/* eslint-disable react/react-in-jsx-scope */
import React, { Component } from 'react';
import { observer, inject } from 'mobx-react'
import {
    View,
    Text,
    FlatList,
    StyleSheet,
    TouchableOpacity,
} from 'react-native';
import { Container, ListFooterComponent } from '../../component';
import Search from './component/Search';
import config from '../../config';

const PAGE_SIZE = 12

const styles = StyleSheet.create({
    container: {
        padding: 8,
        marginTop: 12,
        marginHorizontal: 12,
        borderRadius: 4,
        backgroundColor: '#fff',
    },
    title: {
        color: config.defaultFontColor,
        fontSize: config.defaultFontSize,
    },
    content: {
        marginTop: 8,
        color: config.subTextColor,
        fontSize: config.smallFontSize,
        lineHeight: 16,
    }
});

@inject('speechStore')
@observer
export default class SpeechSearch extends Component {

    componentDidMount() {
        this.props.speechStore.searchByContent(this.props.title, '', 1, PAGE_SIZE)
    }

    _renderItem(item) {
        return (
            <TouchableOpacity style={styles.container}>
                <Text style={styles.title}>{item.title.replace(/^\s+|\s+$/g, '')}</Text>
                <Text style={styles.content}>{item.content}</Text>
            </TouchableOpacity>
        )
    }

    render() {
        const { title, speechStore } = this.props
        const { searchText, formattedSearchList, hasMore, loading } = speechStore
        return (
            <Container
                naviBarProps={{
                    title: title ? title : '搜索',
                }}>

                <Search
                    isEditable
                    onChangeText={(text) => speechStore.searchByContent(title, text, 1, PAGE_SIZE)}
                    value={searchText}
                />

                <FlatList
                    data={formattedSearchList}
                    keyExtractor={(item) => `${item.id}`}
                    ListFooterComponent={() => <ListFooterComponent hasMore={hasMore} />}
                    onEndReached={() => {
                        if (!loading && hasMore) {
                            speechStore.searchByContent(title, searchText, formattedSearchList.length / PAGE_SIZE + 1, PAGE_SIZE)
                        }
                    }}
                    onEndReachedThreshold={0.2}
                    renderItem={({ item }) => this._renderItem(item)}
                />

            </Container>
        )
    }
}